package org.emet.jee.console.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.emet.jee.console.services.sys.ArchManager;
import org.emet.jee.core.dao.arch.CurrentArchHolder;
import org.emet.jee.core.utils.spring.SpringContextHolder;

public class ArchDecisionFilter implements Filter {

	private static final String PARAM_FAILURE_URL = "failureUrl";

	private String failureUrl;

	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException,
			ServletException {
		try {
			HttpServletRequest r = (HttpServletRequest) req;
			Long archId = Long.valueOf(r.getParameter("archSelect"));
			if (archId != null && archId != 0L) {
				// Check if exist!
				ArchManager archMgr = (ArchManager) SpringContextHolder.getBean("archManager");
				if (archMgr.archExists(archId)) {
					CurrentArchHolder.set(r.getSession(true).getId(), archId);
					chain.doFilter(req, resp);
				} else {
					redirectToFail(req, resp);
				}

			} else {
				redirectToFail(req, resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
			redirectToFail(req, resp);
		}

	}

	private void redirectToFail(ServletRequest arg0, ServletResponse arg1) throws IOException {
		((HttpServletResponse) arg1).sendRedirect(((HttpServletRequest) arg0).getContextPath() + failureUrl);
	}

	public void init(FilterConfig arg0) throws ServletException {
		failureUrl = arg0.getInitParameter(PARAM_FAILURE_URL);
	}

}
